<template>
  <div class="width-100-per height-100-per layout-side-n" :style="{height: contentHeight + 'px !important'}">
    <div  class="height-100-per overflow-auto bg-color-white" style="width: 250px">
      <div>
        <a-button-group v-if="userType==='2'" style="padding: 10px 10px 0">
          <a-button style="width: 77px" icon="plus" @click="addArmy">新增</a-button>
          <a-button style="width: 77px" icon="edit" @click="updateArmy">修改</a-button>
          <a-popconfirm title="确定删除该材料类型吗？" placement="topRight" :visible="visibless" @cancel="popconfrmCancels" @visibleChange="visibleChange" @confirm="deleteArmy">
            <a-button style="width: 77px" icon="delete">删除</a-button>
          </a-popconfirm>
        </a-button-group>
      </div>
      <a-input-search style="margin:8px 8px;width: 231px;" placeholder="搜索" @change="onChange"/>
      <div class="layout-left-top width-100-per">
        <span class="width-100-per" v-if="materialData.length<1">暂无数据</span>
        <a-tree
          @select="treeSelects"
          :treeData="materialData"
          defaultExpandAll
          v-if="materialData.length>0"
        >
        </a-tree>
      </div>
    </div>
    <div class="height-100-per overflow-auto padding-left-10-px" style="width: calc(100% - 250px) ">
      <router-view></router-view>
    </div>
    <a-modal
      width="360px"
      :title="armyTitle"
      :visible="modalOrganizational"
      onOk="okOrganizational"
      @cancel="cancelOrganizational"
      okText="确认"
      cancelText="重置">
      <template slot="footer">
        <a-button key="back" @click="handleReset">重置</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="okOrganizational(addOrUpdate)">确认</a-button>
      </template>
      <div class="layout-side">
        <div class="layout-center-top padding-10-px">
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>类型名称</div>
            <a-input class="formInput" v-model="materialType.matTypeName"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>类型编号</div>
            <a-input class="formInput" v-model="materialType.matTypeCode"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>类型上级</div>
<!--            <a-input class="formInput" v-model="materialType.matTypeParentId"></a-input>-->
            <a-tree-select
              class="formInput"
              :value="values"
              :treeData="materialTypesDatas"
              treeDefaultExpandAll
              @select="onSelect"
            />

          </div>
        </div>
      </div>

    </a-modal>
  </div>
</template>

<script>
  import {Tree, Button,Input,Modal,Popconfirm,message,TreeSelect} from 'ant-design-vue'
  import {selectTree} from '../../lib/utils'

  export default {
    name: "index",
    components: {
      // message,
      ATree: Tree,
      AButton: Button,
      AButtonGroup: Button.Group,
      AInputSearch: Input.Search,
      AModal:Modal,
      AInput:Input,
      APopconfirm:Popconfirm,
      ATreeSelect:TreeSelect,
    },
    data(){
      return{
        userType:'0',
        materialTypesIDs:'',
        values:'请选择',
        materialTypesDatas:[],
        visibless:false,
        checkedKey:null,
        loading:false,
        addOrUpdate:0,
        armyTitle:'材料类型修改',
        modalOrganizational:false,
        contentHeight:0,
        materialData:[],
        materialDataBase:[],
        materialType:{
          matTypeName:'',
          matTypeParentId:'',
          matTypeCode:'',
        }
      }
    },
    computed:{
      monitorClientHeight(){
        return this.$store.getters.clientHeight;
      }
    },
    watch:{
      monitorClientHeight:function (old,now) {
        now === 0?this.contentHeight = old -132 : this.contentHeight = old - 132;
      }
    },
    mounted(){
      if(this.$store.getters.clientHeight !== 0){
        this.contentHeight = this.$store.getters.clientHeight - 132;
      }
      this.userType = JSON.parse(this.$store.getters.currentUser).type;
      this.showMaterialTree();
      this.materialP();
    },
    methods: {
      //展示数据字典中树的递归函数
      dataTreeDgData(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.id === t.matTypeParentId) {
            let ct = that.dataTreeDgData(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.matTypeName,
                children: ct,
                key: t.id,
                value: t.id,
                type: 'fatherNode',
              });
            } else {
              newRR.push({
                title: t.matTypeName,
                key: t.id,
                value: t.id,
                type: 'childNode',
              });
            }
          }
        }
        return newRR;
      },
      //上级树选择
      materialP(){
        const that = this;
        that.$apollo.query({
          query:require('../../graphql/material/query/findAllMaterialType.gql'),
          variables:{},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const equipmentTree = data.data.findAllMaterialType;
          const newTree = [];
          for (let r of equipmentTree) {
            if (r.matTypeParentId === '999') {
              let ct = that.dataTreeDgData(r, equipmentTree);
              if (ct.length !== 0) {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                  value: r.id,
                  children: that.dataTreeDgData(r, equipmentTree),
                  type: 'fatherNode',
                })
              } else {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                  value: r.id,
                  type: 'childNode',
                })
              }
            }
          }
          that.materialTypesDatas = [{
            title: '材料总览',
            key: '999',
            value:'999',
            children: newTree
          }];
        }).catch(error=>{
          console.log(error)
        })
      },
      //树组装
      dataTreeDg(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.id === t.matTypeParentId) {
            let ct = that.dataTreeDg(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.matTypeName,
                key: t.id,
                children: ct,
                type: 'fatherNode',
              });
            } else {
              newRR.push({
                title: t.matTypeName,
                key: t.id,
                type: 'childNode',
              });
            }
          }
        }
        return newRR;
      },
      //初始材料分类树
      showMaterialTree(){
        const that = this;
        that.$apollo.query({
          query:require('../../graphql/material/query/findAllMaterialType.gql'),
          variables:{},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const tree = data.data.findAllMaterialType;
          const newTree = [];
          for (let r of tree) {
            if (r.matTypeParentId === '999') {
              let ct = that.dataTreeDg(r, tree);
              if (ct.length !== 0) {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                  children: that.dataTreeDg(r, tree)
                })
              } else {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                })
              }
            }
          }
          that.materialData = [{
            title: '材料总览',
            key: '999',
            children: newTree
          }];
          that.materialDataBase = that.materialData
        }).catch(error=>{
          console.log(error)
        })
      },
      //材料类型上级
      onSelect(value,node,extra){
        this.values=node.title;
        this.materialType.matTypeParentId = value;
      },
      // 关闭删除气泡框
      popconfrmCancels(){
        this.visibless = false;
      },
      //是否弹出
      visibleChange(){
        const that = this;
        // const message = message;
        if(this.checkedKey === null||this.values ==='请选择'){
          this.$message.error('请选择树节点！');
          return
        }
        if(this.checkedKey === '999'){
          this.$message.error('根节点不可删除，请重新选择树节点！');
          return
        }
        this.visibless = true;
      },
      //新增修改提交
      okOrganizational(e){
        const that = this;
        if(that.materialType.matTypeName===""){
          that.$message.error('未输入材料类型名称！');
          return;
        }
        if(that.materialType.matTypeParentId===""){
          that.$message.error('未选择材料类型上级！');
          return;
        }
        if(that.materialType.matTypeCode===""){
          that.$message.error('未输入材料类型编号！');
          return;
        }
        that.loading = true;
        setTimeout(() => {
          that.loading = false;
        }, 500);
        if(that.addOrUpdate === 0){
          if(that.checkedKey !== null){
            that.materialType.matTypeParentId = that.checkedKey;
            that.values = that.checkedKey;
          }else{
            that.materialType.matTypeParentId = '';
            that.values = '请选择';
          }
          that.$apollo.mutate({
            mutation:require('../../graphql/material/mutation/saveMaterialType.gql'),
            variables:{entity:that.materialType},
          }).then((data)=>{
            that.$message.success("新增成功！");
            that.showMaterialTree();
            that.handleReset();
          }).catch(error=>{
            console.log(error);
          })
        }else {
          const addMaterialType = [];
          addMaterialType.push({
            id:that.materialTypesIDs,
            matTypeName:that.materialType.matTypeName,
            matTypeParentId:that.materialType.matTypeParentId,
            matTypeCode:that.materialType.matTypeCode,
          })
          that.$apollo.mutate({
            mutation:require('../../graphql/material/mutation/saveMaterialType.gql'),
            variables:{entity:addMaterialType[0]},
          }).then((data)=>{
            that.$message.success("编辑成功！");
            that.showMaterialTree();
          }).catch(error=>{
            console.log(error);
          })
        }
        that.modalOrganizational = false;

      },

      //重置按钮
      handleReset() {
        this.materialType={
          matTypeName:'',
          matTypeParentId:'',
          matTypeCode:'',
        }
        this.values = "请选择";
      },
      //右上角X按钮
      cancelOrganizational() {
        this.handleReset();
        this.modalOrganizational = false;
      },
      //树选择
      treeSelects(selectedKeys, e){
        if(e.selected === true){
          this.checkedKey=selectedKeys[0];
          this.routerSkip("",{id:selectedKeys[0]});
          this.values = selectedKeys[0];
          this.materialType.matTypeParentId = selectedKeys[0];
          return
        }
        this.checkedKey = null;
        this.values = '请选择';
        this.materialType.matTypeParentId = '';
        this.routerSkip("",{id:'1000'});
      },
      //新增
      addArmy(){
        const that = this;
        that.materialP();
        that.armyTitle = '材料类型新增';
        that.addOrUpdate = 0;
        that.modalOrganizational = true;
      },
      // 修改
      updateArmy(){
        const that = this;
        that.materialP();
        that.armyTitle = '材料类型修改';
        that.addOrUpdate = 1;
        this.$apollo.query({
          query:require('../../graphql/material/query/findMaterialTypeById.gql'),
          variables:{id:this.checkedKey},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const findMaterialTypeById = data.data.findMaterialTypeById;
          that.materialTypesIDs = findMaterialTypeById.id;
          this.materialType={
            matTypeName:findMaterialTypeById.matTypeName,
            matTypeParentId:findMaterialTypeById.matTypeParentId,
            matTypeCode:findMaterialTypeById.matTypeCode,
          }
          that.values = findMaterialTypeById.matTypeParentId;
          that.modalOrganizational = true;
        }).catch((error)=>{
          console.log(error)
        })
      },
      //删除
      deleteArmy(){
        const that = this;
        that.$apollo.mutate({
          mutation:require('../../graphql/material/mutation/deleteMaterialTypeById.gql'),
          variables:{id:that.checkedKey}
        }).then((data)=>{
          that.showMaterialTree();
          that.$message.success("删除成功！");
          that.visibless = false;
        }).catch((error)=>{
          console.log(error)
        })


      },
      //搜索树
      onChange(e) {
        const that = this;
        const value = e.target.value;
        that.materialData = selectTree(value,that.materialDataBase);
      },
    }
  }
</script>

<style scoped>

</style>
